package com.Lemon.Zhkuhealth.provider.service.impl;

import com.Lemon.Zhkuhealth.common.pojo.entity.User;
import com.Lemon.Zhkuhealth.common.util.PageResult;
import com.Lemon.Zhkuhealth.common.util.QueryPageBean;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.Lemon.Zhkuhealh.api.service.IUserService;
import com.Lemon.Zhkuhealth.provider.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
// import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; // 已移除
// import org.springframework.security.crypto.password.PasswordEncoder; // 已移除
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 用户服务实现类
 */
@DubboService
@RequiredArgsConstructor // 如果没有其他 final 字段，你可以移除这个注解，或者保持它
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final UserMapper userMapper;

    @Override
    public PageResult<User> findPage(QueryPageBean queryPageBean) {
        log.info("查询用户列表，当前页: {}, 每页大小: {}, 查询条件: {}",
                queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());

        Page<User> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        // 根据查询字符串对用户名或手机号进行模糊查询
        if (StringUtils.hasText(queryPageBean.getQueryString())) {
            queryWrapper.like(User::getUsername, queryPageBean.getQueryString())
                    .or()
                    .like(User::getTelephone, queryPageBean.getQueryString());
        }

        // 默认按ID降序排序
        queryWrapper.orderByDesc(User::getId);

        Page<User> userPage = userMapper.selectPage(page, queryWrapper);

        return new PageResult<>(userPage.getTotal(), userPage.getRecords());
    }
    public PageResult<User> pageQuery(QueryPageBean queryPageBean) {
        log.info("分页查询用户，当前页: {}，每页大小: {}，查询条件: {}",
                queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());

        Page<User> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(queryPageBean.getQueryString())) {
            queryWrapper.like(User::getUsername, queryPageBean.getQueryString())
                    .or()
                    .like(User::getTelephone, queryPageBean.getQueryString());
        }

        userMapper.selectPage(page, queryWrapper);

        PageResult<User> pageResult = new PageResult<>(page.getTotal(), page.getRecords());
        log.info("分页查询结果: {}", pageResult);
        return pageResult;
    }

    @Override
    @Transactional
    public void add(User user) {
        log.info("新增用户: {}", user);
        // 密码加密逻辑已移除，密码将以明文保存
        // if (StringUtils.hasText(user.getPassword())) {
        //     user.setPassword(passwordEncoder.encode(user.getPassword()));
        // }
        userMapper.insert(user); // 密码将直接插入数据库，不做处理
        log.info("用户新增成功，ID: {}", user.getId());
    }

    @Override
    public User findById(Integer id) {
        log.info("根据ID查询用户: {}", id);
        return userMapper.selectById(id);
    }

    @Override
    @Transactional
    public void edit(User user) {
        log.info("更新用户信息: {}", user);
        // 如果密码不为空，则更新密码（不加密）
        if (StringUtils.hasText(user.getPassword())) {
            // 密码加密逻辑已移除，密码将以明文保存
            // user.setPassword(passwordEncoder.encode(user.getPassword()));
            // 这里不需要额外设置user.setPassword(user.getPassword())，因为对象中已是原值
        } else {
            // 如果密码为空，不更新密码字段，防止覆盖为null
            user.setPassword(null); // 设置为null，MyBatis-Plus会忽略null字段的更新
        }
        userMapper.updateById(user);
        log.info("用户更新成功，ID: {}", user.getId());
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        log.info("删除用户，ID: {}", id);
        userMapper.deleteById(id);
        log.info("用户删除成功，ID: {}", id);
    }

    @Override
    public User findByUsername(String username) {
        log.info("根据用户名查询用户: {}", username);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);
        log.info("查询到用户: {}", user);
        return user;
    }

    @Override
    public User findByUsernameAndPassword(String username, String rawPassword) {
        log.info("尝试登录：用户名: {}", username);
        // 1. 根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(queryWrapper);

        // 2. 检查用户是否存在，并直接验证明文密码
        if (user != null) {
            // --- 修改点：直接比较明文密码 ---
            if (user.getPassword() != null && user.getPassword().equals(rawPassword)) {
                log.info("用户登录成功: {}", username);
                // 登录成功后，出于安全考虑，返回前可以清除用户对象的敏感信息，如密码
                user.setPassword(null);
                return user;
            } else {
                log.warn("用户登录失败：密码不匹配或密码为null，用户名: {}", username);
            }
        } else {
            log.warn("用户登录失败：用户不存在，用户名: {}", username);
        }
        return null; // 用户不存在或密码不匹配
    }
}